/**
  @license
  Copyright 2011 Google Inc. All Rights Reserved.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

gameQueryUrlOldCorp = 'http://spreadsheets.google.com/a/google.com/tq?key=tzo1V5o8Qd3LLDXQwNmp-Ww';
gameQueryUrlNew = 'http://spreadsheets.google.com/a/google.com/tq?key=tzo1V5o8Qd3LLDXQwNmp-Ww&gid=2';
gameQueryUrl = 'https://spreadsheets.google.com/tq?key=0Avnb9NH3ZzOEdFNZSXFobGtzTkxHc3puWVNDMUxFSmc&hl=en&authkey=CNz_tJ0K&pli=1#gid=0';

function createGameChartData(data) {
    var nPlayers = data.getNumberOfRows();
    if (data.getNumberOfColumns() >= 4 && data.getValue(0, 3) > 0) {
      nPlayers = Math.min(nPlayers, data.getValue(0, 3));
    }

    var votes = {};
    for (var i = 0; i < nPlayers; i++) {
      vote = data.getValue(i, 1);
      if (!votes[vote]) {
        votes[vote] = [];
      }
      votes[vote].push(i);
    }

    var winner = -1;
    for (i = 1; i < 1000; i++) {
      if (votes[i] && votes[i].length == 1) {
        winner = i;
        break;
      }
    }
    
    var maxValue = 20;
    while (winner >= maxValue) {
      maxValue = maxValue + 10;
    }

    // Adding all the higher votes to the maxValue.
    votes[maxValue] = 0;
    for (i = maxValue + 1; i < 1000; i++) {
      if (votes[i]) {
        votes[maxValue] += votes[i].length;
      }
    }

    var chartData = new google.visualization.DataTable();
    chartData.addColumn('string', 'Label');
    chartData.addColumn('number', 'Others');
    chartData.addColumn('number', 'You');
    chartData.addColumn('number', 'Winner');


    for (i = 1; i <= maxValue; i++) {
      var winnerValue = winner == i ? 1 : 0;
      var youValue = data.getValue(0, 1) == i ? 1 : 0;
      var value = (votes[i] ? votes[i].length : 0) - youValue - winnerValue;
      chartData.addRow([String(i), value, youValue, winnerValue]);
    }

    return {table: chartData,
	        winnerEmail: winner == -1 ? 'nobody@nowhere.com' : data.getValue(votes[winner][0], 2),
	        winnerValue: winner};
}
